package com.example.studentmanagement2.service.Impl;

import com.example.studentmanagement2.exception.StudentNotFoundException;
import com.example.studentmanagement2.model.Student;
import com.example.studentmanagement2.repository.Repository.StudentRepository;
import com.example.studentmanagement2.service.StudentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class StudentServiceImpl implements StudentService {



    private final StudentRepository studentRepository;

    public StudentServiceImpl(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    @Override
    public List<Student> getAllStudents() {
        return studentRepository.findAll();
    }

    @Override
    public Optional<Student> getStudentById(String id) {
        return Optional.ofNullable(studentRepository.findById(id)
                .orElseThrow(() -> new StudentNotFoundException("Student not found with id: " + id)));
    }

    @Override
    public Student addStudent(Student student) {
        if (studentRepository.existsById(student.getId())) {
            throw new IllegalArgumentException("学号已存在！");
        }
        return studentRepository.save(student);
    }

    // StudentServiceImpl.java
    @Override
    @Transactional
    public Student updateStudent(String originalId, Student student) {
        // 检查原始学号是否存在
        if (!studentRepository.existsById(originalId)) {
            throw new StudentNotFoundException("原始学号不存在");
        }


        // 更新时传入原始学号
        studentRepository.update(student, originalId);
        return student;
    }
    @Override
    public List<Student> searchStudents(String keyword) {
        return studentRepository.search(keyword);
    }

    @Override
    public List<String> findDistinctClasses() {
        return studentRepository.findDistinctClasses();
    }

    @Override
    public void deleteStudent(String id) {
        studentRepository.deleteById(id);
    }
}